package interview.springboot.mybatis.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;

@Configuration
public class MybatisConfig {
    /**
     * 主库数据源配置
     *
     * @return masterDataSourceConf
     */
    @Bean
    @ConfigurationProperties("spring.jdbc.druid")
    public Properties dataSourceConf() {
        return new Properties();
    }


    @Bean(initMethod = "init", destroyMethod = "close")
    public DruidDataSource dataSource(@Qualifier("dataSourceConf") Properties properties) {
        DruidDataSource dataSource = new DruidDataSource();
        Properties config = new Properties();
        for (Object key : properties.keySet()) {
            config.put("druid." + key, properties.get(key));
        }
        dataSource.configFromPropety(config);
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource, ApplicationContext context) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage("interview.springboot.mybatis.entity");
        //避免运行在SpringBoot单独jar中时，找不到资源文件
        sqlSessionFactoryBean.setVfs(SpringBootVFS.class);
        sqlSessionFactoryBean.setMapperLocations(context.getResources("classpath*:*mapper/*.xml"));
        sqlSessionFactoryBean.setConfigLocation(context.getResource("classpath:mybatis-config.xml"));
        return sqlSessionFactoryBean;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("interview.springboot.mybatis.mapper");
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        return mapperScannerConfigurer;
    }
}
